﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.DataDicts.Repository;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Finance.DataDicts
{
    public class DataDictionaryRepository : EfCoreRepository<FinanceDbContext, DataDictionary, Guid>, IDataDictionaryRepository
    {
        public DataDictionaryRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<DataDictionary>> FindAsync(DataDictPageQuery query)
        {
            var dataDictionaries = await DbContext.Set<DataDictionary>().AsNoTracking()
             .WhereIf(!query.ModuleCode.IsNullOrEmpty(), x => x.ModuleCode==query.ModuleCode)
             .WhereIf(!query.Key.IsNullOrEmpty(), x => x.Key == query.Key)
             .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
             .WhereIf(query.Activated.HasValue, x => x.Activated == query.Activated.Value)
             .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
             .ToListAsync();

            return dataDictionaries;
        }

        public async Task<int> GetCountAsync(DataDictPageQuery query)
        {
            int count = await DbContext.Set<DataDictionary>().AsNoTracking()
                .WhereIf(!query.ModuleCode.IsNullOrEmpty(), x => x.ModuleCode == query.ModuleCode)
                .WhereIf(!query.Key.IsNullOrEmpty(), x => x.Key == query.Key)
                .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
                .WhereIf(query.Activated.HasValue, x => x.Activated == query.Activated.Value)
                .CountAsync();

            return count;
        }
    }
}
